package com.leather.news.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leather.common.result.CodeMsg;
import com.leather.common.result.Result;
import com.leather.common.toolkits.CheckKit;
import com.leather.common.toolkits.JwtKit;
import com.leather.news.service.JwService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JwController {

    @Autowired
    private JwService jwService;

    @GetMapping("/getgrade")
    public Result getGrade(@RequestHeader("token") String token, @RequestParam("xq") String xq) {
        String number = JwtKit.getValue(token);
        CheckKit.notEmpty(number, CodeMsg.ERROR_TOKEN);
        CheckKit.notEmpty(xq, CodeMsg.ERROR_XQ);
        return jwService.getGrade(number, xq);
    }

    @GetMapping("/getindex")
    public Result getIndex(@RequestHeader("token") String token) {
        String number = JwtKit.getValue(token);
        CheckKit.notEmpty(number, CodeMsg.ERROR_TOKEN);
        Result grade = jwService.getGrade(number, "2018-2019-2");
        JSONArray grades = new JSONArray(), kss = new JSONArray();
        if (grade.isSuccess()) {
            grades = (JSONArray) grade.getData();
        }
        Result ks = jwService.getKS(number);
        if (ks.isSuccess()) {
            kss = (JSONArray) ks.getData();
        }
        int chengji = grades.size();
        float xuefen = 0;
        int kscount = kss.size();
        for (Object obj : grades) {
            JSONObject jsonObjectobj = (JSONObject) obj;
            String xf = jsonObjectobj.getString("xf");
            xuefen += Float.parseFloat(xf.trim());
        }
        JSONObject object = new JSONObject();
        object.put("ks", "最近有 " + kscount + " 门考试");
        object.put("cj", "共 " + chengji + " 门课程,总学分 " + xuefen);
        return Result.success(object);
    }

    @GetMapping("/getkebiao")
    public Result getKebiao(@RequestHeader("token") String token) {

        String number = JwtKit.getValue(token);
        CheckKit.notEmpty(number, CodeMsg.ERROR_TOKEN);
        return jwService.getTodayKebiao(number);
    }

    @GetMapping("getks")
    public Result getKs(@RequestHeader("token") String token) {
        String number = JwtKit.getValue(token);
        CheckKit.notEmpty(number, CodeMsg.ERROR_TOKEN);
        return jwService.getKS(number);
    }

}
